package cn.newgrand.netcall.integration.sms;

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import org.jivesoftware.resource.Res;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smackx.packet.VCard;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.component.TitlePanel;
import org.jivesoftware.spark.util.ResourceUtils;
import org.jivesoftware.spark.util.log.Log;
import org.jivesoftware.sparkimpl.profile.VCardManager;

import cn.newgrand.netcall.common.StringUtilCommon;
import cn.newgrand.netcall.smackx.integration.AppSysBindPhoneIQ;

/**
 * 手机绑定通过发送激活码开通短信功能
 * @author sww
 *
 */
public class PhoneBindingPanel extends JPanel{

	private static final long serialVersionUID = 1L;
	private JLabel telephoneLable = new JLabel();
	private JTextField telephoneField = new JTextField(12);
	private JButton gainActivationCode = new JButton();
	private JLabel activationCodeLabel = new JLabel();
	private JTextField activationCodeField = new JTextField();
	private JButton bindPhoneButton = new JButton();
	private JButton unBindPhoneButton = new JButton();
	private JButton changeBindPhoneButton = new JButton();
	
	private SMS sms = new SMS();
	private SMSContact smsContactSender;
	private SMSContact smsContactReceiver;
	private String activationCode = StringUtilCommon.gainRandomNum();
	private VCard vcard = null;

	public PhoneBindingPanel(){
		this.setLayout(new GridBagLayout());
		ResourceUtils.resLabel(telephoneLable, telephoneField, "手机号码:");
		ResourceUtils.resButton(gainActivationCode, "获取激活码");
		ResourceUtils.resLabel(activationCodeLabel, activationCodeField, "激活码:");
		ResourceUtils.resButton(bindPhoneButton, "绑定");
		ResourceUtils.resButton(unBindPhoneButton, "解绑");
		ResourceUtils.resButton(changeBindPhoneButton, "更换");
		gainActivationCode.setEnabled(false);
		bindPhoneButton.setEnabled(false);
		activationCodeField.setEnabled(false);
		unBindPhoneButton.setEnabled(false);
		changeBindPhoneButton.setEnabled(false);
		this.add(telephoneLable, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
		this.add(telephoneField, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
		this.add(gainActivationCode, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
		this.add(activationCodeLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
		this.add(activationCodeField, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
		String phone = "";
		if(SMSManager.bindPhone != null && !"".equals(SMSManager.bindPhone)){
			phone = SMSManager.bindPhone;
			this.add(changeBindPhoneButton, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
			this.add(unBindPhoneButton, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
		}else{
			String bareJid = SparkManager.getSessionManager().getBareAddress();
			try {
				vcard = SparkManager.getVCardManager().reloadVCard(bareJid);
				phone = vcard.getPhoneWork("CELL");
			} catch (Exception e) {
				vcard = SparkManager.getVCardManager().getVCard(bareJid);
				phone = vcard.getPhoneWork("CELL");
			}
			this.add(bindPhoneButton, new GridBagConstraints(1, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
		}
		
		if(phone != null && !"".equals(phone)){
			telephoneField.setText(phone);
			String reg = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
			boolean b = phone.matches(reg);
			if(b){
				gainActivationCode.setEnabled(true);
			}else{
				gainActivationCode.setEnabled(false);
			}
		}
		activationCodeField.addKeyListener(new KeyListener() {
			
			@Override
			public void keyTyped(KeyEvent e) {
				
			}
			
			@Override
			public void keyReleased(KeyEvent e) {
				String inputField = activationCodeField.getText();
				if(activationCode.equals(inputField)){
					bindPhoneButton.setEnabled(true);
					unBindPhoneButton.setEnabled(true);
					changeBindPhoneButton.setEnabled(true);
				}else{
					bindPhoneButton.setEnabled(false);
					unBindPhoneButton.setEnabled(false);
					changeBindPhoneButton.setEnabled(false);
				}
			}
			
			@Override
			public void keyPressed(KeyEvent e) {
				
			}
		});
		gainActivationCode.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				smsContactSender = new SMSContact();
				String sender = SparkManager.getSessionManager().getUsername();
				smsContactSender.setJid(sender);
				sms.setSender(smsContactSender);
				String content = "尊敬的用户你手机绑定的激活码为:"+activationCode+"[来自NETCALL消息,请勿回复]";
				System.out.println(content); 
				sms.setContent(content);
				List<SMSContact> receivers = new ArrayList<SMSContact>();
				smsContactReceiver = new SMSContact();
				String phone = telephoneField.getText();
				smsContactReceiver.setPhone(phone);
				receivers.add(smsContactReceiver);
				sms.setReceivers(receivers);
				try {
					SMSManager.getInstance().sendSMS(sms,SMSManager.UNREPLY);
				} catch (Exception exception) {
					Log.error(exception.getMessage(),exception);
				}
				activationCodeField.setEnabled(true);
				gainActivationCode.setEnabled(false);
				telephoneField.setEnabled(false);
			}
		});
		telephoneField.addKeyListener(new KeyListener() {
			
			@Override
			public void keyTyped(KeyEvent e) {
				
			}
			
			@Override
			public void keyReleased(KeyEvent e) {
				if(telephoneField.getText().length() > 11){
					gainActivationCode.setEnabled(false);
					return;
				}else{
					String telephone = telephoneField.getText();
					String reg = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
					boolean b = telephone.matches(reg);
					if(b){
						gainActivationCode.setEnabled(true);
					}else{
						gainActivationCode.setEnabled(false);
					}
				}
			}
			
			@Override
			public void keyPressed(KeyEvent e) {
				
			}
		});
		
		createDialog();
	}

	private void createDialog() {
		final JOptionPane pane;
        final JDialog dlg;

        TitlePanel titlePanel;

        // Create the title panel for this dialog
        titlePanel = new TitlePanel("手机绑定/解绑", "获取激活码后,绑定/更换/解绑手机,绑定的手机号码会同步更新到个人资料工作中的移动电话", SparkRes.getImageIcon(SparkRes.BLANK_24x24), true);

        // Construct main panel w/ layout.
        final JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(titlePanel, BorderLayout.NORTH);
        
        // The user should only be able to close this dialog.
        Object[] options = {Res.getString("close")};
        pane = new JOptionPane(this, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, options, options[0]);
        
        mainPanel.add(pane, BorderLayout.CENTER);

        JOptionPane p = new JOptionPane();
        dlg = p.createDialog(SparkManager.getMainWindow(), "手机绑定/解绑");
        dlg.pack();
        dlg.setSize(320, 300);
        dlg.setContentPane(mainPanel);
        dlg.setLocationRelativeTo(SparkManager.getMainWindow());
        
        unBindPhoneButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				AppSysBindPhoneIQ bindPhoneIQ = new AppSysBindPhoneIQ();
				bindPhoneIQ.setBindPhone(telephoneField.getText());
				bindPhoneIQ.setBindType("unbind");
				bindPhoneIQ.setType(IQ.Type.SET);
				bindPhoneIQ.setTo("integration." + SparkManager.getConnection().getServiceName());
				final PacketCollector collector = SparkManager.getConnection().createPacketCollector(new PacketIDFilter(bindPhoneIQ.getPacketID()));
				SparkManager.getConnection().sendPacket(bindPhoneIQ);
				AppSysBindPhoneIQ result = (AppSysBindPhoneIQ)collector.nextResult(5*1000);
				if(result != null && "success".equals(result.getResult())){
					SMSManager.bindPhone = null;
					JOptionPane.showMessageDialog(mainPanel, "解绑成功", "消息", JOptionPane.INFORMATION_MESSAGE);
					dlg.dispose();
				}else{
					JOptionPane.showMessageDialog(mainPanel, "解绑失败", "消息", JOptionPane.INFORMATION_MESSAGE);
					dlg.dispose();
				}
			}
		});
        
        changeBindPhoneButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(telephoneField.getText().equals(SMSManager.bindPhone)){
					JOptionPane.showMessageDialog(mainPanel, "该号码您已经绑定,不需要更换", "消息", JOptionPane.INFORMATION_MESSAGE);
					return;
				}else{
					AppSysBindPhoneIQ result = bindOrChangePhone();
					if(result != null && "success".equals(result.getResult())){
						updateVcardPhone();
						SMSManager.bindPhone = telephoneField.getText();
						JOptionPane.showMessageDialog(mainPanel, "更换成功", "消息", JOptionPane.INFORMATION_MESSAGE);
						dlg.dispose();
					}else if(result != null&& "binded".equals(result.getResult())){
						JOptionPane.showMessageDialog(mainPanel, "你所输入的手机号码和"+result.getReason()+"一致,请更改", "消息", JOptionPane.INFORMATION_MESSAGE);
						telephoneField.setEnabled(true);
						bindPhoneButton.setEnabled(false);
						activationCodeField.setText("");
						activationCodeField.setEnabled(false);
						//dlg.dispose();
					}else{
						JOptionPane.showMessageDialog(mainPanel, "更换失败", "消息", JOptionPane.INFORMATION_MESSAGE);
						dlg.dispose();
					}
				}
			}
		});

        bindPhoneButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				AppSysBindPhoneIQ result = bindOrChangePhone();
				if(result != null&& "success".equals(result.getResult())){
					updateVcardPhone();
					SMSManager.bindPhone = telephoneField.getText();
					JOptionPane.showMessageDialog(mainPanel, "绑定成功", "消息", JOptionPane.INFORMATION_MESSAGE);
					dlg.dispose();
				}else if(result != null&& "binded".equals(result.getResult())){
					JOptionPane.showMessageDialog(mainPanel, "你所输入的手机号码和"+result.getReason()+"一致,请更改", "消息", JOptionPane.INFORMATION_MESSAGE);
					telephoneField.setEnabled(true);
					bindPhoneButton.setEnabled(false);
					activationCodeField.setText("");
					activationCodeField.setEnabled(false);
					//dlg.dispose();
				}else{
					JOptionPane.showMessageDialog(mainPanel, "绑定失败", "消息", JOptionPane.INFORMATION_MESSAGE);
					dlg.dispose();
				}
			}
		});

        PropertyChangeListener changeListener = new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent e) {
                Object o = pane.getValue();
                if (o instanceof Integer) {
                    dlg.setVisible(false);
                    return;
                }

                String value = (String)pane.getValue();
                if (Res.getString("close").equals(value)) {
                    dlg.setVisible(false);
                }
            }

        };

        pane.addPropertyChangeListener(changeListener);
        dlg.setResizable(true);
        dlg.setVisible(true);
        dlg.toFront();
        dlg.requestFocus();
	}
	
	/**
	 * 更换或绑定手机号码
	 * @return
	 */
	public AppSysBindPhoneIQ bindOrChangePhone(){
		AppSysBindPhoneIQ bindPhoneIQ = new AppSysBindPhoneIQ();
		bindPhoneIQ.setBindPhone(telephoneField.getText());
		bindPhoneIQ.setBindType("bind");
		bindPhoneIQ.setType(IQ.Type.SET);
		bindPhoneIQ.setTo("integration." + SparkManager.getConnection().getServiceName());
		final PacketCollector collector = SparkManager.getConnection().createPacketCollector(new PacketIDFilter(bindPhoneIQ.getPacketID()));
		SparkManager.getConnection().sendPacket(bindPhoneIQ);
		AppSysBindPhoneIQ result = (AppSysBindPhoneIQ)collector.nextResult(5*1000);
		return result;
	}
	
	private void updateVcardPhone(){
		String phone = vcard.getPhoneWork("CELL");
		if(!telephoneField.getText().equals(phone)){
			vcard.setPhoneWork("CELL", telephoneField.getText());
			final VCardManager vcardManager = SparkManager.getVCardManager();
            vcardManager.setPersonalVCard(vcard);
            try {
				vcard.save(SparkManager.getConnection());
			} catch (XMPPException e1) {
				e1.printStackTrace();
			}
		}
	}

}
